package com.badibadi.mail;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.alipay.android.msp.Keys;
import com.alipay.android.msp.Result;
import com.alipay.android.msp.SignUtils;
import com.alipay.sdk.app.PayTask;
import com.badibadi.activity.RechargeActivity;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

//四、图13 和6 同意支付，但是没有付款
/**
 * 常数已改 答方：等待乙方付款 问方：点击立即支付付款 立即支付成功后：---》 queding
 * 
 * @author Administrator
 * 
 */
public class Mail13_6Activity extends Mail67Activity {
	private Results results3;
	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_CHECK_FLAG = 2;
	// 分润的
	private String fenrun_money;
	public Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(Mail13_6Activity.this);
				try {
					Utils.showMessage(Mail13_6Activity.this, getResources()
							.getString(R.string.l_net_error));
					// Intent intent=new
					// Intent(Mail13_6Activity.this,Mail8_14_15Activity.class);
					finish();

				} catch (Exception e) {
				}
				break;
			case 3:
				try {
					Utils.ExitPrgress(Mail13_6Activity.this);
					Utils.showMessage(Mail13_6Activity.this, getResources()
							.getString(R.string.wx_txt_105));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 7:
				try {
					Utils.ExitPrgress(Mail13_6Activity.this);
					if (results3.isRet()) {
						try {
							String info = getOrderInfo(results3.getRetmsg(),
									getResources().getString(R.string.l_xb173),
									fenrun_money,
									getResources().getString(R.string.l_xb172)
											+ fenrun_money);
							String sign = sign(info);
							try {
								// 仅需对sign 做URL编码
								sign = URLEncoder.encode(sign, "UTF-8");
							} catch (UnsupportedEncodingException e) {
								   
							}
							final String payInfo = info + "&sign=\"" + sign
									+ "\"&" + getSignType();
//							   
							Runnable payRunnable = new Runnable() {
								@Override
								public void run() {
									// 构造PayTask 对象
									PayTask alipay = new PayTask(
											Mail13_6Activity.this);
									// 调用支付接口
									String result = alipay.pay(payInfo);

									Message msg = new Message();
//									   
									msg.what = SDK_PAY_FLAG;
									msg.obj = result;
									mHandler2sd.sendMessage(msg);
								}
							};

							Thread payThread = new Thread(payRunnable);
							payThread.start();
						} catch (Exception ex) {
							   
							Toast.makeText(Mail13_6Activity.this,
									R.string.remote_call_failed,
									Toast.LENGTH_SHORT).show();
						}

					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			}
		}

	};
	private Handler mHandler2sd = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				Result resultObj = new Result((String) msg.obj);
				String resultStatus = resultObj.resultStatus;

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(Mail13_6Activity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					Mail13_6Activity.this.finish();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”
					// 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(Mail13_6Activity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						Toast.makeText(Mail13_6Activity.this, "支付失败",
								Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(Mail13_6Activity.this, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void DongTaiPeiZhi() {
		// TODO Auto-generated method stub

		TextView tishi = (TextView) this.findViewById(R.id.tishi);
		tishi.setText(getResources().getString(R.string.wx_zhixunfei_kuohao));
		tishi.setVisibility(View.VISIBLE);

		if (rank.equals("answerer")) {
			Button shedingzhixunfei = (Button) this
					.findViewById(R.id.shedingzhixunfei);
			shedingzhixunfei.setText(getResources().getString(
					R.string.wx_chakan_zhixunfei));
			shedingzhixunfei.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					LayoutInflater inflater = LayoutInflater
							.from(Mail13_6Activity.this);
					View view = inflater
							.inflate(R.layout.chakanzhixunfei, null);

					// 支付宝手续费
					TextView alipay_charge = (TextView) view
							.findViewById(R.id.alipay_charge);
//					   
//							+ payUserContactShow1Model.getAlipay_charge());
					alipay_charge.setText(""
							+ payUserContactShow1Model.getAlipay_charge());
					// 达人
					TextView expert_charge = (TextView) view
							.findViewById(R.id.expert_charge);
					expert_charge.setText(""
							+ payUserContactShow1Model.getExpert_charge());
					// 一般用户
					TextView member_charge = (TextView) view
							.findViewById(R.id.member_charge);
					member_charge.setText(""
							+ payUserContactShow1Model.getMember_charge());
					// 显示的费用
					TextView et_feiyong = (TextView) view
							.findViewById(R.id.feiyong);
					et_feiyong.setText(""
							+ payUserContactShow1Model.getZhannei_usercontact()
									.get(0).getFees());
					// 退款工作日
					TextView replay_limit_time = (TextView) view
							.findViewById(R.id.replay_limit_time);
					replay_limit_time.setText(""
							+ payUserContactShow1Model.getReplay_limit_time());

					Button quxiao = (Button) view.findViewById(R.id.quxiao);
					quxiao.setText(getResources().getString(R.string.wx_txt_80));

					// et_feiyong.setText();
					al_sheding = new AlertDialog.Builder(Mail13_6Activity.this)
							.setView(view).show();
				}
			});
			shedingzhixunfei.setVisibility(View.VISIBLE);
			this.findViewById(R.id.delete).setVisibility(View.GONE);
		} else // 这是问方
		{
			mhandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					showWenFangView();
				}
			}, 500);
			Button shedingzhixunfei = (Button) this
					.findViewById(R.id.shedingzhixunfei);
			shedingzhixunfei.setText(getResources().getString(
					R.string.wx_chakan_zhixunfei));
			shedingzhixunfei.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					showWenFangView();
				}
			});
			shedingzhixunfei.setVisibility(View.VISIBLE);
			this.findViewById(R.id.delete).setVisibility(View.GONE);
		}
	}

	public void showWenFangView() {
		LayoutInflater inflater = LayoutInflater.from(Mail13_6Activity.this);
		View view = inflater.inflate(R.layout.lijizhifu, null);

		// 支付宝手续费
		TextView alipay_charge = (TextView) view
				.findViewById(R.id.alipay_charge);
		alipay_charge.setText("" + payUserContactShow1Model.getAlipay_charge());
		// 达人
		TextView expert_charge = (TextView) view
				.findViewById(R.id.expert_charge);
		expert_charge.setText("" + payUserContactShow1Model.getExpert_charge());
		// 一般用户
		TextView member_charge = (TextView) view
				.findViewById(R.id.member_charge);
		member_charge.setText("" + payUserContactShow1Model.getMember_charge());
		// 显示的费用
		TextView et_feiyong = (TextView) view.findViewById(R.id.feiyong);
		et_feiyong.setText(""
				+ payUserContactShow1Model.getZhannei_usercontact().get(0)
						.getFees());

		// 立即支付按钮，这个会链接到支付宝
		Button queding = (Button) view.findViewById(R.id.queding);
		queding.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// zhifu();
				// 模拟他支付成功了
				// mhandler.sendEmptyMessage(1);
				// PayUtils.fenrui(Mail13_6Activity.this,
				// payUserContactShow1Model.getContent_id(),
				// payUserContactShow1Model.getUid(), ""
				// + payUserContactShow1Model
				// .getZhannei_usercontact().get(0)
				// .getFees());
				// finish();
				fenrui(payUserContactShow1Model.getContent_id(),
						payUserContactShow1Model.getUid(), ""
								+ payUserContactShow1Model
										.getZhannei_usercontact().get(0)
										.getFees());

			}

		});

		// et_feiyong.setText();
		al_sheding = new AlertDialog.Builder(Mail13_6Activity.this).setView(
				view).show();
	}

	/**
	 * 
	 * @param ct
	 * @param yonghulianxixiaoxiid
	 *            （用户联系消息的id）
	 * @param target_id
	 *            订单受益人的id （一定为答方id）
	 * @param money
	 *            支付的金额
	 */
	public void fenrui(final String yonghulianxixiaoxiid,
			final String target_id, final String money) {
		fenrun_money = money;
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				// list = new ArrayList<Activity_Overview_Model>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(Mail13_6Activity.this));
				map.put("zhannei_usercontact_id", yonghulianxixiaoxiid);
				map.put("target_id", target_id);
				map.put("money", money);
//				   
				String actcontent = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "order/zhannei");
				if (actcontent != null) {
//					   
					results3 = Utils.checkResult_NNN(Mail13_6Activity.this,
							actcontent);
					if (results3 != null
							&& !results3.getRetmsg().equals("null")) {
//						   
						mhandler.sendEmptyMessage(7);
					} else {
						mhandler.sendEmptyMessage(3);
					}
				} else {
					mhandler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void zhifu() {
		// TODO Auto-generated method stub

	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String dingdanhao, String body, String price,
			String info) {
		// 合作者身份ID
		String orderInfo = "partner=" + "\"" + Keys.DEFAULT_PARTNER + "\"";

		// 卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + Keys.DEFAULT_SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + dingdanhao + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + info + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\""
				+ "http://www.uniclubber.com/App/APPpay/notifyurl.html" + "\"";

		// 接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, Keys.RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
